DAY34:Human readable duration format


Posted by birdbirdmurmur on 2023-08-16

題目連結

https://www.codewars.com/kata/52742f58faf5485cae000b9a

解法

function formatDuration(seconds) {
    if (seconds === 0) {
        return 'now'
    }

    const result = []
    const units = [
        { name: 'year', value: 365 * 24 * 60 * 60 },
        { name: 'day', value: 24 * 60 * 60 },
        { name: 'hour', value: 60 * 60 },
        { name: 'minute', value: 60 },
        { name: 'second', value: 1 }
    ]

    for (const unit of units) {
        if (seconds >= unit.value) {
            const count = Math.floor(seconds / unit.value)
            seconds %= unit.value
            result.push(`${count} ${unit.name}${count > 1 ? 's' : ''}`)
        }
    }
    if (result.length > 1) {
        const last = result.pop();
        return result.join(", ") + " and " + last;
    } else {
        return result[0];
    }
}

筆記

進階版的秒數換算
建立一個units array 包含不同時間單位的資訊
使用for...of迴圈遍歷units
設定count計算每個單位的數量
使用模板字串結合unit.name
使用三元運算子判斷是否需要在unit.name後加's'
根據陣列的長度
多使用pop()'and'處理多種情況
或返回result[0]


#javascript #Codewars #pop







Related Posts

【Day05】實戰開始 - 區塊分割

【Day05】實戰開始 - 區塊分割

變數命名的善意

變數命名的善意

Aspect-Oriented Programming(AOP) 面向導向程式

Aspect-Oriented Programming(AOP) 面向導向程式


Comments